import { ApiGetTodoList, ApiGetTodoListById } from '@/services/apis/todo'
import {
  socket,
  SocketTodoCreate,
  SocketTodoUpdate,
  SocketTodoDelete
} from '@/services/webSockets/todo'
import { defineStore } from 'pinia'
import { reactive } from 'vue'

import type {
  IListItem,
  ICreateListDto,
  IGetListDto,
  IUpdateListDto
} from './interfaces/list.interface'

export const useTodoListStore = defineStore('todo-list', () => {
  const todoList = reactive<{ [key: number]: IListItem[] }>({})
  getAllList()

  function getAllList() {
    Promise.allSettled([getList(0), getList(1), getList(2), getList(3), getList(4), getList(5)])
  }

  async function getListById(id: string) {
    return await ApiGetTodoListById(id)
  }

  socket.on('todo-create', (res: boolean) => {
    console.log('todo-create', res)
    res && getAllList()
  })

  socket.on('todo-update', (res: boolean) => {
    console.log('todo-update', res)
    res && getAllList()
  })

  socket.on('todo-delete', (res: boolean) => {
    console.log('todo-delete', res)
    res && getAllList()
  })

  async function createList(payload: ICreateListDto) {
    SocketTodoCreate(payload)
    return true
  }

  async function deleteList(id: string) {
    SocketTodoDelete(id)
    return true
  }

  /* @todo **/
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  async function clearAllList() {}

  async function getList(pageId = 0) {
    const payload: IGetListDto = { limit: 20, pageId }
    const { list = [] } = await ApiGetTodoList(payload)
    todoList[pageId] = list
  }

  async function updateList(payload: IUpdateListDto) {
    SocketTodoUpdate(payload)
    return true
  }

  return {
    todoList,

    getList,
    getListById,
    createList,
    updateList,
    deleteList,
    clearAllList
  }
})
